<!--船舶排布-->
<template>
  <div>
    <div class="hightChart-gantt">
      <div class="chart-head" v-if="ganttConfig.tableConfig.length > 0">
        <div class="chart-down">
          <a-button class="border-btn"  @click="exportCharts">
            <template #icon>
              <UploadOutlined />
            </template>
            导出</a-button>
        </div>
        <div>
          <div class="moth-flex">
            <div v-for="item in  dateTypes" :key="item.value"
                 :class="{
                  'month-item-btn': true,
                   'month-item-btn-active': scaleUnit === item.value
                 }"
                 @click="changeDate(item.value )">{{item.label}}</div>
            <div  :class="{
                  'month-item-btn': true,
                   'month-item-btn-active': scaleUnit === 'day'
                 }" @click="changeDate('day')">今天</div>
          </div>
        </div>
      </div>
      <div class="chart-border" v-if="ganttConfig.tableConfig.length > 0"></div>
      <div id="containerResArrge" ref="containerResArrge"></div>
      <!--    <div id="test-container"></div>-->
      <!--  详情编辑抽屉   -->
      <a-drawer
          v-model:visible="visible"
          :width="520"
          class="custom-class"
          :title="`货号：${ganttInfo.goodsNum}`"
          placement="right"
          :drawerStyle="drawStyle"
          @after-visible-change="afterVisibleChange"
      >
        <template #extra>
          <!--          <a-button style="margin-right: 8px" class="search-btn2" @click="showDeleteModal">删除</a-button>-->
          <a-button class="search-btn1" @click="showChildrenDrawer">查看</a-button>
        </template>
        <div class="drawer-body">
          <div class="info-list">
            <div class="info-item">
              <div class="info-title">航次号</div>
              <div class="info-val">{{ganttInfo.voyageNo}}</div>
            </div>
            <div class="info-item">
              <div class="info-title">资源合同·采购</div>
              <div class="info-val">{{ganttInfo.contractName}}</div>
            </div>
            <div class="info-item">
              <div class="info-title">资源合同·销售</div>
              <div class="info-val">{{ganttInfo.sellerContractName}}</div>
            </div>
            <div class="info-item">
              <div class="info-title">资源方</div>
              <div class="info-val">{{ganttInfo.seller}}</div>
            </div>
            <div class="info-item">
              <div class="info-title">买方</div>
              <div class="info-val">{{ganttInfo.buyer}}</div>
            </div>
            <div class="info-item">
              <div class="info-title">贸易类型·采购</div>
              <div class="info-val">{{ganttInfo.tradeTypeLabel}}</div>
            </div>
            <div class="info-item">
              <div class="info-title">贸易主体·采购</div>
              <div class="info-val">{{ganttInfo.tradeBodyLabel}}</div>
            </div>
            <div class="info-item">
              <div class="info-title">贸易主体·销售</div>
              <div class="info-val">{{ganttInfo.sellerTradeBodyLabel}}</div>
            </div>
            <a-divider />
            <div class="info-item">
              <div class="info-title">预计装载时间</div>
              <div class="info-val">{{ganttInfo.expectedLoadingDate}}</div>
            </div>
            <div class="info-item">
              <div class="info-title">实际装载时间</div>
              <div class="info-val">{{ganttInfo.realityLoadingDate}}</div>
            </div>
            <div class="info-item">
              <div class="info-title">预计卸载完成窗口</div>
              <div class="info-val">{{ganttInfo.expectedUnloadingWindow}}</div>
            </div>
            <div class="info-item">
              <div class="info-title">装载港</div>
              <div class="info-val">{{ganttInfo.expectedLoadingPort}}</div>
            </div>
            <div class="info-item">
              <div class="info-title">卸载港</div>
              <div class="info-val">{{ganttInfo.expectedUnloadingPort}}</div>
            </div>
            <div class="info-item">
              <div class="info-title">合同装载量</div>
              <div class="info-val">{{ganttInfo.loadingCapacity}}</div>
            </div>
            <div class="info-item">
              <div class="info-title">实际装载量</div>
              <div class="info-val">{{ganttInfo.realityLoadingCapacity}}</div>
            </div>
            <a-divider />
            <div class="info-item">
              <div class="info-title">船速</div>
              <div class="info-val">{{ganttInfo.shipSpeed}}</div>
            </div>
            <div class="info-item">
              <div class="info-title">航线</div>
              <div class="info-val">
                {{ganttInfo.shipRouteLabel}}
              </div>
            </div>
            <div class="info-item">
              <div class="info-title">油耗</div>
              <div class="info-val">{{ganttInfo.oilConsumptionString}}</div>
            </div>
            <div class="info-item">
              <div class="info-title">船舶名称</div>
              <div class="info-val">{{ganttInfo.shipName}}</div>
            </div>
            <div class="info-item">
              <div class="info-title">IMO</div>
              <div class="info-val">{{ganttInfo.imo}}</div>
            </div>
            <div class="info-item">
              <div class="info-title">贸易主体·船舶</div>
              <div class="info-val">{{ganttInfo.shipTradeBodyLabel}}</div>
            </div>
            <a-divider />
            <div class="info-item">
              <div class="info-title">巴拿马运河预定时间</div>
              <div class="info-val">{{ganttInfo.panamaCanalReservationDate}}</div>
            </div>
            <div class="info-item">
              <div class="info-title">换港时间1</div>
              <div class="info-val">{{ganttInfo.portChangeDateOne}}</div>
            </div>
            <div class="info-item">
              <div class="info-title">换港时间2</div>
              <div class="info-val">{{ganttInfo.portChangeDateTwo}}</div>
            </div>
            <div class="info-item">
              <div class="info-title">换船/指船时间1</div>
              <div class="info-val">{{ganttInfo.shipChangeDateOne}}</div>
            </div>
            <div class="info-item">
              <div class="info-title">换船时间2</div>
              <div class="info-val">{{ganttInfo.shipChangeDateTwo}}</div>
            </div>
            <a-divider />
            <div class="info-item">
              <div class="info-title">预计满载航程天数</div>
              <div class="info-val">{{ganttInfo.expectedFullLoadVoyageDays}}</div>
            </div>
            <div class="info-item">
              <div class="info-title">预计卸载时间·回国</div>
              <div class="info-val">{{ganttInfo.expectedUnloadingWindow}}</div>
            </div>
            <div class="info-item">
              <div class="info-title">预计卸载时间·欧洲</div>
              <div class="info-val">{{ganttInfo.europeUnloadTime}}</div>
            </div>
            <div class="info-item">
              <div class="info-title">预计卸载时间·印度</div>
              <div class="info-val">{{ganttInfo.indiaUnloadTime}}</div>
            </div>
            <div class="info-item">
              <div class="info-title">预计卸载完成时间</div>
              <div class="info-val">{{ganttInfo.expectedUnloadingCompletionWindow}}</div>
            </div>
            <a-divider />
            <div class="info-item">
              <div class="info-title">预计空载航程天数</div>
              <div class="info-val">{{ganttInfo.expectedEmptyLoadVoyageDays}}</div>
            </div>
            <div class="info-item">
              <div class="info-title">预计空载返程时间</div>
              <div class="info-val">{{ganttInfo.expectedEmptyReturnWindow}}</div>
            </div>
            <div class="info-item">
              <div class="info-title">实际卸载时间</div>
              <div class="info-val">{{ganttInfo.realityUnloadingDate}}</div>
            </div>
            <div class="info-item">
              <div class="info-title">是否审批</div>
              <div class="info-val">{{ganttInfo.schemeApprove === 1? '未审批': '已审批'}}</div>
            </div>
            <div class="info-item">
              <div class="info-title">状态</div>
              <div class="info-val">
                <span v-for="item in planType" :key="item.value">
                  <span v-if="item.value === ganttInfo.executeStatus">
                    {{item.label}}
                  </span>
                </span>
              </div>
            </div>
            <div class="info-item">
              <div class="info-title">备注</div>
              <div class="info-val">{{ganttInfo.remark}}</div>
            </div>
          </div>
        </div>
        <a-drawer
            v-model:visible="childrenDrawer"
            title="编辑"
            width="1150"
            :footer-style="{ textAlign: 'center' }"
        >
          <div class="form-box">
            <div class="form-box-item">
              <div class="box-item-head">
                当前方案
              </div>
              <div class="form-content">
                <div class="content-item">
                  <a-descriptions :column="2" :labelStyle="labelStyle">
                    <a-descriptions-item label="时间">{{newHistory.createDate}}</a-descriptions-item>
                    <a-descriptions-item label="优化人">{{newHistory.createBy}}</a-descriptions-item>
                    <a-descriptions-item label="运费">{{newHistory.ship}}</a-descriptions-item>
                    <a-descriptions-item label="贸易利润率">{{newHistory.trade}}</a-descriptions-item>
                  </a-descriptions>
                  <div class="form-item-border">
                    <a-form-item label="船舶名称">
                      <a-input :bordered="false" disabled v-model:value="newHistory.shipName"  placeholder="请输入"/>
                    </a-form-item>
                  </div>
                  <div class="form-item-border">
                    <a-form-item label="舱容">
                      <a-input :bordered="false" disabled v-model:value="newHistory.loadingCapacityString" placeholder="请输入"/>
                    </a-form-item>
                  </div>
                  <div class="form-item-border">
                    <a-form-item label="满载航程天数">
                      <a-input :bordered="false" disabled v-model:value="newHistory.expectedFullLoadVoyageDays"  placeholder="请输入"/>
                    </a-form-item>
                  </div>
                  <div class="form-item-border">
                    <a-form-item label="空载航程天数">
                      <a-input :bordered="false" disabled v-model:value="newHistory.expectedEmptyLoadVoyageDays"  placeholder="请输入"/>
                    </a-form-item>
                  </div>
                  <div class="form-item-border">
                    <a-form-item label="空载返程窗口">
                      <a-input :bordered="false" disabled v-model:value="newHistory.expectedEmptyReturnWindow"  placeholder="请输入"/>
                    </a-form-item>
                  </div>
                  <div class="item-ul" v-if="ganttHistory.length> 0">
                    <div class="item-li">
                      <div class="li-label">优化记录：</div>
                      <a-button class="info-btn" @click="goHistoryInfo(newHistory.planId)">查看详情</a-button>
                    </div>
                  </div>
                </div>
                <div class="content-scroll">
                  <div class="content-item" v-for="item in ganttHistory" :key="item.id">
                    <a-descriptions :column="2" :labelStyle="labelStyle">
                      <a-descriptions-item label="时间">{{item.createDate}}</a-descriptions-item>
                      <a-descriptions-item label="优化人">{{item.createBy}}</a-descriptions-item>
                      <a-descriptions-item label="运费">{{item.ship}}</a-descriptions-item>
                      <a-descriptions-item label="贸易利润率">{{item.trade}}</a-descriptions-item>
                    </a-descriptions>
                    <div class="form-item-border">
                      <a-form-item label="船舶名称">
                        <a-input :bordered="false" disabled v-model:value="item.shipName"  placeholder="请输入"/>
                      </a-form-item>
                    </div>
                    <div class="form-item-border">
                      <a-form-item label="舱容">
                        <a-input :bordered="false" disabled v-model:value="item.loadingCapacityString" placeholder="请输入"/>
                      </a-form-item>
                    </div>
                    <div class="form-item-border">
                      <a-form-item label="满载航程天数">
                        <a-input :bordered="false" disabled v-model:value="item.expectedFullLoadVoyageDays"  placeholder="请输入"/>
                      </a-form-item>
                    </div>
                    <div class="form-item-border">
                      <a-form-item label="空载航程天数">
                        <a-input :bordered="false" disabled v-model:value="item.expectedEmptyLoadVoyageDays"  placeholder="请输入"/>
                      </a-form-item>
                    </div>
                    <div class="form-item-border">
                      <a-form-item label="空载返程窗口">
                        <a-input :bordered="false" disabled v-model:value="item.expectedEmptyReturnWindow"  placeholder="请输入"/>
                      </a-form-item>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <a-divider type="vertical" :style="{height: '2000px'}"/>
            <div class="form-box-item">
              <div class="box-item-head">
                基础信息
              </div>
              <div class="form-content">
                <div class="content-item">
                  <div class="form-item-border">
                    <a-form-item label="资源合同·采购">
                      <a-select :bordered="false" disabled v-model:value="formState.contractName" placeholder="请选择资源合同"  />
                    </a-form-item>
                  </div>
                  <div class="form-item-border">
                    <a-form-item label="资源合同·销售">
                      <a-select :bordered="false" disabled v-model:value="formState.sellerContractName" placeholder="请选择资源·销售合同"/>
                    </a-form-item>
                  </div>
                  <div class="form-item-border">
                    <a-form-item label="资源方">
                      <a-input :bordered="false" disabled v-model:value="formState.seller"  placeholder="请输入"/>
                    </a-form-item>
                  </div>
                  <div class="form-item-border">
                    <a-form-item label="买方">
                      <a-input :bordered="false" disabled v-model:value="formState.buyer"  placeholder="请输入"/>
                    </a-form-item>
                  </div>
                  <div class="form-item-border">
                    <a-form-item label="贸易类型·采购" name="tradeType">
                      <a-input :bordered="false" disabled v-model:value="formState.tradeTypeLabel"  placeholder="请输入"/>
                    </a-form-item>
                  </div>
                  <div class="form-item-border">
                    <a-form-item label="贸易主体·采购" name="tradeBody">
                      <a-select :bordered="false"  disabled v-model:value="formState.tradeBody" placeholder="请选择贸易主体" :options="tradeareas" />
                    </a-form-item>
                  </div>
                  <div class="form-item-border">
                    <a-form-item label="贸易主体·销售" name="sellerTradeBody">
                      <a-select :bordered="false"  disabled v-model:value="formState.sellerTradeBody" placeholder="请选择贸易主体" :options="tradeareas" />
                    </a-form-item>
                  </div>
                  <a-divider/>
                  <div class="form-item-border">
                    <a-form-item label="装载港">
                      <a-tree-select
                          disabled
                          :bordered="false"
                          v-model:value="formState.expectedLoadingPort"
                          style="width: 100%"
                          :tree-data="portTree"
                          tree-checkable
                          allow-clear
                          :height="233"
                          :show-checked-strategy="SHOW_CHILD"
                          placeholder="请选择装载港"
                          tree-node-filter-prop="label"
                          :max-tag-count="2"
                      />
                    </a-form-item>
                  </div>
                  <div class="form-item-border">
                    <a-form-item label="卸载港">
                      <a-tree-select
                          :bordered="false"
                          disabled
                          v-model:value="formState.expectedUnloadingPort"
                          style="width: 100%"
                          :tree-data="portTree"
                          tree-checkable
                          allow-clear
                          :height="233"
                          :show-checked-strategy="SHOW_CHILD"
                          placeholder="请选择装载港"
                          tree-node-filter-prop="label"
                          :max-tag-count="2"
                      />
                    </a-form-item>
                  </div>
                  <div class="form-item-border">
                    <a-form-item label="合同装载量">
                      <a-input-number :bordered="false" disabled v-model:value="formState.loadingCapacity" :style="{width: '100%'}" placeholder="请输入装载量"  :min="1" >
                        <template #addonAfter>
                          <a-select  style="width: 100px" v-model:value="formState.quantityUnit">
                            <a-select-option :value="1">MMBtu</a-select-option>
                            <a-select-option :value="2">m³</a-select-option>
                            <a-select-option :value="3">MT</a-select-option>
                          </a-select>
                        </template>
                      </a-input-number>
                    </a-form-item>
                  </div>
                  <div class="form-item-border">
                    <a-form-item label="实际装载量">
                      <a-input-number disabled :bordered="false" v-model:value="formState.realityLoadingCapacity"  placeholder="请输入"/>
                    </a-form-item>
                  </div>
                  <div class="form-item-border">
                    <a-form-item label="预计装载时间">
                      <a-date-picker :bordered="false" disabled :style="{width: '100%'}" v-model:value="formState.expectedLoadingDate" show-time value-format="YYYY-MM-DD HH:mm:ss" />
                    </a-form-item>
                  </div>
                  <div class="form-item-border">
                    <a-form-item label="实际装载时间">
                      <a-date-picker :bordered="false" disabled :style="{width: '100%'}" v-model:value="formState.expectedLoadingDate" show-time value-format="YYYY-MM-DD HH:mm:ss" />
                    </a-form-item>
                  </div>
                  <a-divider/>
                  <div class="form-item-border">
                    <a-form-item label="预计装载完成窗口">
                      <a-date-picker :bordered="false" disabled :style="{width: '100%'}" v-model:value="formState.expectedLoadingCompletionWindow" show-time value-format="YYYY-MM-DD HH:mm:ss" />
                    </a-form-item>
                  </div>
                  <div class="form-item-border">
                    <a-form-item label="巴拿马运河预定时间">
                      <a-input-number :bordered="false" addonAfter="天"
                                      disabled
                                      v-model:value="formState.panamaCanalReservationDate" :style="{width: '100%'}" placeholder="请输入"
                      />
                    </a-form-item>
                  </div>
                  <div class="form-item-border">
                    <a-form-item label="换港时间1">
                      <a-date-picker :bordered="false" disabled :style="{width: '100%'}" v-model:value="formState.portChangeDateOne" show-time value-format="YYYY-MM-DD HH:mm:ss" />
                    </a-form-item>
                  </div>
                  <div class="form-item-border">
                    <a-form-item label="换港时间2">
                      <a-date-picker :bordered="false" disabled :style="{width: '100%'}" v-model:value="formState.portChangeDateTwo" show-time value-format="YYYY-MM-DD HH:mm:ss" />
                    </a-form-item>
                  </div>
                  <div class="form-item-border">
                    <a-form-item label="换船/指船时间1">
                      <a-date-picker :bordered="false" disabled :style="{width: '100%'}" v-model:value="formState.shipChangeDateOne" show-time value-format="YYYY-MM-DD HH:mm:ss" />
                    </a-form-item>
                  </div>
                  <div class="form-item-border">
                    <a-form-item label="换船时间2">
                      <a-date-picker :bordered="false" disabled :style="{width: '100%'}" v-model:value="formState.shipChangeDateTwo" show-time value-format="YYYY-MM-DD HH:mm:ss" />
                    </a-form-item>
                  </div>
                  <a-divider/>
                  <div class="form-item-border">
                    <a-form-item label="预计满载航程天数">
                      <a-input-number :bordered="false" addonAfter="天"
                                      disabled
                                      v-model:value="formState.expectedFullLoadVoyageDays" :style="{width: '100%'}" placeholder="请输入"
                      />
                    </a-form-item>
                  </div>
                  <div class="form-item-border">
                    <a-form-item label="预计卸载时间·中国">
                      <a-date-picker :bordered="false" disabled  :style="{width: '100%'}" v-model:value="formState.expectedUnloadingWindow" show-time value-format="YYYY-MM-DD HH:mm:ss" />
                    </a-form-item>
                  </div>
                  <div class="form-item-border">
                    <a-form-item label="预计卸载时间·欧洲">
                      <a-date-picker :bordered="false" disabled :style="{width: '100%'}" v-model:value="formState.europeUnloadTime" show-time value-format="YYYY-MM-DD HH:mm:ss" />
                    </a-form-item>
                  </div>
                  <div class="form-item-border">
                    <a-form-item label="预计卸载时间·印度">
                      <a-date-picker :bordered="false" disabled :style="{width: '100%'}"  v-model:value="formState.indiaUnloadTime" show-time value-format="YYYY-MM-DD HH:mm:ss" />
                    </a-form-item>
                  </div>
                  <div class="form-item-border">
                    <a-form-item label="预计卸载完成时间">
                      <a-date-picker :bordered="false" disabled :style="{width: '100%'}"  v-model:value="formState.expectedUnloadingCompletionWindow" show-time value-format="YYYY-MM-DD HH:mm:ss" />
                    </a-form-item>
                  </div>
                  <div class="form-item-border">
                    <a-form-item label="预计空载航程天数">
                      <a-input-number :bordered="false" addonAfter="天"
                                      disabled
                                      v-model:value="formState.expectedEmptyLoadVoyageDays" :style="{width: '100%'}" placeholder="请输入"
                      />
                    </a-form-item>
                  </div>
                  <div class="form-item-border">
                    <a-form-item label="预计空载返程时间">
                      <a-date-picker :bordered="false" disabled :style="{width: '100%'}"  v-model:value="formState.expectedEmptyReturnWindow" show-time value-format="YYYY-MM-DD HH:mm:ss" />
                    </a-form-item>
                  </div>
                  <div class="form-item-border">
                    <a-form-item label="实际卸载时间">
                      <a-date-picker :bordered="false" disabled :style="{width: '100%'}"  v-model:value="formState.realityUnloadingDate" show-time value-format="YYYY-MM-DD HH:mm:ss" />
                    </a-form-item>
                  </div>
                  <a-divider/>
                  <div class="form-item-border">
                    <a-form-item label="船舶名称">
                      <a-input :bordered="false" disabled v-model:value="formState.shipName"  placeholder="请输入"/>
                    </a-form-item>
                  </div>
                  <div class="form-item-border">
                    <a-form-item label="IMO">
                      <a-input :bordered="false" disabled v-model:value="formState.imo"  placeholder="请输入"/>
                    </a-form-item>
                  </div>
                  <div class="form-item-border">
                    <a-form-item label="贸易主体·船舶">
                      <a-select :bordered="false"  disabled v-model:value="formState.shipTradeBody" placeholder="请选择贸易主体" :options="tradeareas" />
                    </a-form-item>
                  </div>
                  <a-divider/>
                  <a-form-item label="航线">
                    <a-checkbox-group  style="width: 100%" v-model:value="formState.shipRoute" disabled>
                      <a-row>
                        <a-col class="custom-checkobox" :span="8" v-for="item in AirOptions" :key="item.value">
                          <a-checkbox :value="item.value">{{item.label}}</a-checkbox>
                        </a-col>
                      </a-row>
                    </a-checkbox-group>
                  </a-form-item>
                  <div class="form-item-border">
                    <a-form-item label="船速">
                      <a-input-number :bordered="false" addonAfter="节"
                                      disabled
                                      v-model:value="formState.shipSpeed" :style="{width: '100%'}" placeholder="请输入船速"
                                      :max="19.5"
                                      :min="12" />
                    </a-form-item>
                  </div>
                  <div class="form-item-border">
                    <a-form-item label="油耗">
                      <a-input :bordered="false" disabled v-model:value="formState.oilConsumption"  placeholder="请输入"/>
                    </a-form-item>
                  </div>
                  <a-divider/>
                  <div class="form-item-border">
                    <a-form-item label="备注">
                      <a-textarea :bordered="false" disabled="" v-model:value="formState.remark"  placeholder="请输入"/>
                    </a-form-item>
                  </div>
                  <a-form-item label="是否审批">
                    <a-radio-group v-model:value="formState.schemeApprove" disabled>
                      <a-radio :value="1">是</a-radio>
                      <a-radio :value="2">否</a-radio>
                    </a-radio-group>
                  </a-form-item>
                  <a-form-item label="状态">
                    <a-radio-group v-model:value="formState.executeStatus" disabled>
                      <a-radio :value="0">未下发</a-radio>
                      <a-radio :value="1">已下发</a-radio>
                      <a-radio :value="2">已排布</a-radio>
                      <a-radio :value="3">已完成</a-radio>
                      <a-radio :value="4">已终止</a-radio>
                    </a-radio-group>
                  </a-form-item>
                </div>
              </div>
            </div>
          </div>
          <template  #footer>
            <a-button style="margin-right: 26px"  key="back" class="border-btn" @click="onClose">取消</a-button>
            <a-button key="submit" @click="onSubmitForm" class="search-btn1">保存</a-button>
          </template>
        </a-drawer>
      </a-drawer>
      <!--删除弹框-->
      <a-modal v-model:visible="deleteVisible" :width="450" title="终止原因"  @ok="handleOk">
        <a-form :model="deleteFormState" labelAlign="left" :label-col="labelCol" :wrapper-col="wrapperCol">
          <a-row>
            <a-col :span="24">
              <div class="form-item-border" :style="{height: '100%'}">
                <a-form-item label="备注" name="reasonMsg">
                  <a-textarea :bordered="false" :autoSize="{minRows: 4, maxRows: 10}" v-model:value="deleteFormState.reasonMsg" :row="8" placeholder="请输入终止原因，经审批后，该船货不再执行"/>
                </a-form-item>
              </div>
            </a-col>
          </a-row>
        </a-form>
        <template #footer>
          <div class="from-btn-right">
            <a-button key="back" class="border-btn" @click="cacelDeleteModel">取消</a-button>
            <a-button key="submit" @click="handleOk" class="search-btn1">保存</a-button>
          </div>
        </template>
      </a-modal>
    </div>
    <EmptyDefault :style="{margin: '30px'}" v-if='ganttConfig.tableConfig.length === 0' :descriptionInfo="'暂无数据'"/>
  </div>
</template>
<script setup>
import {defineEmits, defineProps, getCurrentInstance, onBeforeUnmount, onMounted, ref, watch} from 'vue';
import EmptyDefault from '@/components/EmptyDefault/EmptyDefault.vue'
import { useRouter } from "vue-router";
const router = useRouter()
const { proxy  } = getCurrentInstance()
const emit = defineEmits(['dropChange', 'dropChangeVal', 'exportImg'])
import { UploadOutlined} from '@ant-design/icons-vue';
import { TreeSelect } from 'ant-design-vue';
const SHOW_CHILD = TreeSelect.SHOW_CHILD;
// 引入
import Highcharts from 'highcharts/highcharts-gantt.src.js'
import exportingInit from 'highcharts/modules/exporting'
// 引入拖拽
import factory from 'highcharts/modules/draggable-points.js'
factory(Highcharts)
exportingInit(Highcharts)
import dayjs from 'dayjs'
import html2canvas from "html2canvas";
import {message} from "ant-design-vue";
const props = defineProps({
  activeKey: {
    type: String,
    default: ''
  },
  ganttConfig: {
    type: Object,
    default: () => {}
  },
  isRedraw: {
    type: Number,
    default: 0
  },
  allExport: {
    type: Boolean,
    default: false
  },
  firstShipLoadingTime: {
    type: Number,
    default: 0
  }
})
const dateTypes = ref([
  {
    label: '周',
    value: 'week'
  },
  {
    label: '月',
    value: 'month'
  },
  {
    label: '季',
    value: 'quarter'
  },
  {
    label: '年',
    value: 'year'
  }
])
const planType = ref([
  {
    label: '未下发',
    value: 0
  },
  {
    label: '已下发',
    value: 1
  },
  {
    label: '执行中',
    value: 2
  },
  {
    label: '已完成',
    value: 3
  },
  {
    label: '已终止',
    value: 4
  }
])
const scaleUnit = ref('year')
const changeDate = (type) => {
  scaleUnit.value = type
  sessionStorage.setItem('scaleUnitResArrge', scaleUnit.value)
  toggleTimeDimension(type)
}
watch(() => props.allExport, () => {
  exportChartsAll()
})
watch(() => props.isRedraw, () => {
  init()
})
const ganttData = ref(props.ganttConfig)
watch(() => props.ganttConfig, (newVal) => {
  if (newVal){
    ganttData.value = newVal
  }
})
const labelStyle = ref({
  color: '#6B7A8B'
})
// 贸易主体
const tradeareas = ref([
  {
    label: '国贸',
    value: 1
  },
  {
    label: '新贸',
    value: 2
  },
])
// 航线
const AirOptions = ref([
  {
    label: '巴拿马运河',
    value:'1'
  },
  {
    label: '好望角海峡',
    value:'2'
  },
  {
    label: '苏伊士运河',
    value:'3'
  }
])
const portTree = ref([])
const portChildren = ref([])
const flagStates = ref([]) //船旗国
const gantt = ref({});
/**
 * 获取船旗国
 * */
const flagList = () => {
  flagStates.value = []
  proxy.$api.getFlagStates().then(res => {
    const data = res.resultObject
    data.map(item => {
      let newObj = {}
      Object.assign(newObj, {
        label: item,
        value: item
      })
      flagStates.value.push(newObj)
    })
  })
}
/**
 * 获取港口信息
 * */
const getPortsList = () => {
  portTree.value = []
  proxy.$api.getPortInfo().then(res => {
    const data = res.resultObject
    data.map(item => {
      let ports = {
        label: '',
        value: '',
        children: [{
          label: '',
          value: '',
        }]
      }
      if (item.loadingPorts) {
        item.loadingPorts.map(child => {
          Object.assign(child, {
            label: child.portNameChinese,
            value: child.id.toString(),
          })
          portChildren.value.push(child)
        })
      }
      Object.assign(ports, {
        label: item.country,
        value: item.country,
        children: item.loadingPorts
      })
      portTree.value.push(ports)
      console.log('港口信息',  portTree.value)
    })
  })
}
// 官方建议用UTC的时间，鉴于业务需要，我们需要和数据库时间保持统一，得看数据库的存储格式
//计算本年的周数
const getWeekNumber = (dates) => {
  const d = new Date(Date.UTC(dates.getFullYear(), dates.getMonth(), dates.getDate()));
  const dayNum = d.getUTCDay() || 7; d.setUTCDate(d.getUTCDate() + 4 - dayNum);
  const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
  const weekNum = Math.ceil((((d - yearStart) / 86400000) + 1) / 7)
  const year = dates.getFullYear()
  let januaryFirst = new Date(year, 0, 1);
  let daysOffset = (weekNum - 1) * 7;

  // 计算指定周的开始日期
  let startDate = new Date(januaryFirst);
  startDate.setDate(januaryFirst.getDate() + daysOffset - januaryFirst.getDay() + 1);

  // 计算指定周的结束日期
  let endDate = new Date(startDate);
  endDate.setDate(startDate.getDate() + 6);
  return `${dayjs(startDate).format('D')}-${dayjs(endDate).format('D')}`
};

// 全局配置，需要在图标初始化之前配置
Highcharts.setOptions({
  global: {
    useUTC: false  // 不使用utc时间
  },
  lang: {
    noData: '暂无数据',
    months: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
    shortMonths: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
    weekdays: ['日', '一', '二', '三', '四', '五', '六'],
    rangeSelectorZoom: '范围',
    contextButtonTitle:"图表导出菜单",
    decimalPoint:".",
    downloadJPEG:"下载JPEG图片",
    downloadPDF:"下载PDF文件",
    downloadPNG:"下载PNG文件",
    downloadSVG:"下载SVG文件",
    printChart:"打印图表",
    resetZoom:"恢复缩放",
    resetZoomTitle:"恢复图表",
  },
});
const dragStart = (e) => {
  console.log('拖拽开始时', e)
  oldData.value = JSON.parse(JSON.stringify(ganttData.value.data))
  console.log('原来的数据', oldData.value)
}
let oldData = ref([])
const drag = (e) => {
  // 拖拽过程中
  // const firstKeys = Object.keys(e.origin.points)[0]
  // 旧的Y的index
  // let oldY = e.origin.points[firstKeys]
  // let newY = e.target.y
  return e.target.draggable
}
const drop = (e) => {
  console.log('拖拽l', e)
}
// 选中，可以弹窗，编辑一些业务数据
const handleSelect = (e) => {
  console.log('选中', e)
  showDrawer(e)
  getPortsList()
  return false
}
/**
 * 导出到压缩包
 * */
const exportChartsAll = () => {
  let chartContainer = document.getElementById("containerResArrge");
  html2canvas(chartContainer, {
    backgroundColor: '#fff'
  }).then((canvas) => {
    let imgData = canvas.toDataURL('image/png')
    let obj = {
      name: '货源排布',
      imgData: imgData
    }
    emit('exportImg', obj)
  })
}
// 导出为png
const exportCharts = () => {
  let chartContainer = document.getElementById("containerResArrge");
  html2canvas(chartContainer, {
    backgroundColor: '#fff'
  }).then((canvas) => {
    let imgData = canvas.toDataURL('image/png')
    let img = new Image()
    img.src = imgData
    console.log('导出的数据', imgData)
    // 创建一个隐藏的链接元素用于下载
    let a = document.createElement('a');
    a.href = imgData;
    a.download = '货源排布.png'; // 设置下载文件名
    // 模拟点击下载链接
    a.style.display = 'none';
    document.body.appendChild(a);
    a.click();
    // 清理下载链接元素
    document.body.removeChild(a);
  })
}
// 切换日期范围
const  toggleTimeDimension = (interval) => {
  const filteredArray = Highcharts.charts.filter((element) => element !== undefined);
  var chart = filteredArray[2];
  console.log('我的chartA', filteredArray, interval)
  var xAxis = chart.xAxis[0];
  var xAxis2 = chart.xAxis[1];
  switch (interval) {
    case 'year':
      const minYears = Date.now()
      const lastYears = Date.now() + 365 * 24 * 3600 * 1000
      xAxis.setExtremes(minYears, lastYears)
      xAxis.update({
        tickInterval: 30 * 24 * 3600 * 1000, // 月
        grid: {
          borderWidth: 1, // 右侧表头边框宽度
          cellHeight: 0, // 右侧日期表头高度
        },
        labels: {
          step:1,
          align: 'center',
          formatter: function() {
            const date = new Date(this.value);
            return Highcharts.dateFormat('%b', date)
          }
        },
      })
      xAxis2.update({
        tickPixelInterval: 365 * 24 * 3600 * 1000,
        labels: {
          align: 'center',
          formatter: function() {
            const date = new Date(this.value)
            return Highcharts.dateFormat('%Y', date)
          }
        }
      })
      break
    case 'month':
      const minMonth = Date.now()
      let lastDate = ''
      if (window.screen.width < 1920) {
        lastDate = Date.now() + 27 * 24 * 3600 * 1000
      } else {
        lastDate = Date.now() + 30.44 * 24 * 3600 * 1000
      }
      xAxis.setExtremes(minMonth, lastDate)
      xAxis.update({
        tickInterval: 24 * 3600 * 1000, // 天
        grid: {
          borderWidth: 1, // 右侧表头边框宽度
          cellHeight: 0, // 右侧日期表头高度
        },
        labels: {
          align: 'center',
          formatter: function() {
            const date = new Date(this.value);
            return Highcharts.dateFormat('%d', date)
          }
        },
      })
      xAxis2.update({
        tickPixelInterval: 30.44 * 24 * 3600 * 1000,
        labels: {
          align: 'center',
          formatter: function() {
            const date = new Date(this.value)
            return Highcharts.dateFormat('%Y-%m', date)
          }
        },
      })
      break
    case 'week':
      const minMonths = Date.now()
      const lastDates = Date.now() + 7 * 24 * 3600 * 1000
      xAxis.setExtremes(minMonths, lastDates)
      xAxis.update({
        tickInterval: 24 * 3600 * 1000, // 天
        grid: {
          borderWidth: 1, // 右侧表头边框宽度
          cellHeight: 0, // 右侧日期表头高度
        },
        labels: {
          align: 'center',
          formatter: function() {
            const date = new Date(this.value);
            return Highcharts.dateFormat('%d', date)
          }
        },
      })
      xAxis2.update({
        tickPixelInterval: 30.44 * 24 * 3600 * 1000,
        labels: {
          align: 'center',
          formatter: function() {
            const date = new Date(this.value)
            return Highcharts.dateFormat('%Y-%m', date)
          }
        },
      })
      break
    case 'quarter':
      const minQuarter = Date.now()
      let lastQuarter = Date.now() + 3 * 30.44 * 24 * 3600 * 1000
      xAxis.setExtremes(minQuarter, lastQuarter)
      xAxis.update({
        tickInterval: 7 * 24 * 3600* 1000, // 7天
        labels: {
          formatter: function () {
            const date = new Date(this.value);
            const weekDate =getWeekNumber(date);
            return `${weekDate}`
          }
        }
      })
      xAxis2.update({
        tickPixelInterval: 30.44 * 24 * 3600 * 1000,
        labels: {
          align: 'center',
          formatter: function() {
            const date = new Date(this.value)
            return Highcharts.dateFormat('%Y-%m', date)
          }
        },
      })
      break
    case 'day':
      const minDay = Date.now()
      let lastDateDay = ''
      if (window.screen.width < 1920) {
        lastDateDay = Date.now() + 27 * 24 * 3600 * 1000
      } else {
        lastDateDay = Date.now() + 30.44 * 24 * 3600 * 1000
      }
      console.log('点击了今天')
      xAxis.setExtremes(minDay, lastDateDay)
      xAxis.update({
        tickInterval: 24 * 3600 * 1000, // 天
        grid: {
          borderWidth: 1, // 右侧表头边框宽度
          cellHeight: 0, // 右侧日期表头高度
        },
        labels: {
          align: 'center',
          formatter: function() {
            const date = new Date(this.value);
            return Highcharts.dateFormat('%d', date)
          }
        },
      })
      xAxis2.update({
        tickPixelInterval: 30.44 * 24 * 3600 * 1000,
        labels: {
          align: 'center',
          formatter: function() {
            const date = new Date(this.value)
            return Highcharts.dateFormat('%Y-%m', date)
          }
        },
      })
      break
  }

  chart.redraw();
}
const containerResArrge = ref(null)
const init = () => {
  sessionStorage.setItem('scaleUnitResArrge', scaleUnit.value)
  if (ganttData.value.tableConfig.length > 0) {
    gantt.value = Highcharts.ganttChart(containerResArrge.value, {
      chart: {
        // backgroundColor: "#364766",
        // scrollablePlotArea: {
        //   minWidth: 300
        // }
        spacingBottom: 100,
        events: {
          redraw: function () {
          },
          selection: function (event) {
            console.log('滚动的', event)
          }
        }
      },
      xAxis: [{
        currentDateIndicator: true,
        type: 'datetime',
        gridLineColor: '#DCDEE0',
        lineColor: '#DCDEE0',
        grid: {
          borderColor: '#DCDEE0',
          borderWidth: 1, // 右侧表头边框宽度
          cellHeight: 0, // 右侧日期表头高度
        },
        tickInterval: 30 * 24 * 3600 * 1000,
        labels: {
          style: {
            color: '#2C3749',
            fontSize: '14px'
          },
          align: 'center',
          formatter: function () {
            const date = new Date(this.value);
            return Highcharts.dateFormat('%b', date)
          }
        },
        // plotLines: [
        //   {
        //     color: 'red', // 线的颜色
        //     width: 2,     // 线的宽度
        //     value: Date.UTC(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()), // 时间戳
        //     zIndex: 4,     // zIndex 用于控制图形元素的显示层级
        //     label: {
        //       text: '今天', // 线的标签
        //       align: 'top', // 标签对齐方式
        //     }
        //   }
        // ]
      },
        {
          tickPixelInterval: 365 * 24 * 3600 * 1000,
          gridLineColor: '#DCDEE0',
          lineColor: '#DCDEE0',
          // gridLineWidth: 0,
          grid: {
            borderColor: '#DCDEE0',
            borderWidth: 1, // 右侧表头边框宽度
            cellHeight: 0, // 右侧日期表头高度
          },
          labels: {
            style: {
              color: '#2C3749',
              fontSize: '14px'
            },
            align: 'center',
            formatter: function () {
              const date = new Date(this.value)
              return Highcharts.dateFormat('%Y', date)
            }
          },
        }],
      scrollbar: {
        enabled: true    //是否显示滚动条
      },
      navigator: {
        enabled: true,
        height: 20,
        // maskInside: false,
        // adaptToUpdatedData: false,
        outlineColor: 'transparent',
        series: {
          type: 'gantt',
          pointPlacement: 0.5,
          pointPadding: 0.25,
          data: []
        },
        yAxis: {
          reversed: false,
          lables: {
            enabled: false
          },
          categories: []
        },
        xAxis: {
          enabled: false,
          gridLineColor: 'transparent',
          labels: {
            format: '{value: %Y-%m-%d}'
          },
          events: {
            afterSetExtremes: function (e) {
              console.log('滑动的', e)
              // const leftHandlePosition = this.navigator.leftHandle && this.navigator.leftHandle.x || 0;
              // const rightHandlePosition = this.navigator.rightHandle && this.navigator.rightHandle.x || 0;

              // if (leftHandlePosition > rightHandlePosition) {
              //   const newMin = this.min + (leftHandlePosition - rightHandlePosition);
              //   const newMax = this.max + (leftHandlePosition - rightHandlePosition);
              //   this.setExtremes(newMin, newMax, false);
              // }
            }
          },
        },
      },
      yAxis: {
        type: 'category',
        reversed: true,
        title: {
          text: '资源方',
          useHTML: true,
          style: {
            fontSize: '14px',
            color: '#2C3749',
            paddingBottom: '50px'
          }
        },
        gridLineColor: '#DCDEE0',
        lineColor: '#DCDEE0',
        minorGridLineColor: '#DCDEE0',
        grid: {
          borderColor: '#DCDEE0',
        },
        labels: {
          style: {
            color: '#2C3749',
            fontSize: '14px'
          }
        },
        categories: ganttData.value.tableConfig,
      },
      tooltip: {
        backgroundColor: 'rgba(255,255,255,0.9)',
        borderColor: '#fff',
        shadow: false,
        borderWidth: 0,
        padding: 16,
        style: {
          fontSize: '16px',
        },
        useHTML: true,
        formatter: function () {
          let content = `<div>
              <div style="margin-bottom: 12px"><span style="color: #6B7A8B" >船舶名称:</span> <span style="color: #2C3749">${this.point.shipName}（${this.point.imo}）</span></div>
              <div style="margin-bottom: 12px"><span style="color: #6B7A8B" >预计装载时间:</span> <span style="color: #2C3749">${dayjs(this.point.start).format('YYYY-MM-DD HH:mm:ss')}</span></div>
              <div style="margin-bottom: 12px"><span style="color: #6B7A8B" >贸易主体:</span> <span style="color: #2C3749">${this.point.tradeBodyLabel}</span></div>
              <div style="margin-bottom: 12px"><span style="color: #6B7A8B" >资源方:</span> <span style="color: #2C3749">${this.point.goodsNum}</span></div>
              <div style="margin-bottom: 12px"><span style="color: #6B7A8B" >预计卸载时间（中国):</span> <span style="color: #2C3749">${dayjs(this.point.expectedUnloadingWindow).format('YYYY-MM-DD HH:mm:ss')}</span></div>
              <div style="margin-bottom: 12px"><span style="color: #6B7A8B" >预计卸载时间·欧洲:</span> <span style="color: #2C3749">${dayjs(this.point.europeUnloadTime).format('YYYY-MM-DD HH:mm:ss')}</span></div>
              <div style="margin-bottom: 12px"><span style="color: #6B7A8B" >预计卸载时间·印度:</span> <span style="color: #2C3749">${dayjs(this.point.indiaUnloadTime).format('YYYY-MM-DD HH:mm:ss')}</span></div>
               <div style="margin-bottom: 12px"><span style="color: #6B7A8B" >预计空载返程时间:</span> <span style="color: #2C3749">${dayjs(this.point.end).format('YYYY-MM-DD HH:mm:ss')}</span></div>
              </div>`
          return content
        }
      },
      series: [{data: ganttData.value.data}],
      plotOptions: {
        series: {
          animation: false,     // Do not animate dependency connectors
          dragDrop: {
            draggableX: false,   // 横向拖拽
            draggableY: false,   // 纵向拖拽
            dragMinY: 0,        // 纵向拖拽下限
            dragMaxY: ganttData.value.tableConfig.length - 1,        // 纵向拖拽上限
            dragPrecisionX: 3600   // 横向拖拽精度，单位毫秒
          },
          dataLabels: {
            enabled: true,
            format: '{point.seller}',
            style: {
              cursor: 'default',
              pointerEvents: 'none'
            }
          },
          allowPointSelect: true,
          point: {
            events: {
              dragStart: dragStart,
              drag: drag,
              drop: drop,
              select: handleSelect
            }
          }
        }
      },
      // 顶部筛选按钮
      rangeSelector: {
        enabled: false,
        selected: 0,
        // buttons: [
        //   { type: 'month', count: 1, text: '月' },
        //   { type: 'month', count: 3, text: '季度' },
        //   { type: 'month', count: 6, text: '半年' },
        //   { type: 'ytd', text: 'YTD' },
        //   { type: 'year', count: 1, text: '年' },
        //   { type: 'all', text: '所有' },
        // ],
      },
      exporting: {
        enabled: false,
        sourceWidth: 1000,
        // sourceHight: gantt.value.chartHight,
      },
      credits: {    // 去掉右下角版权信息
        enabled: false
      },
    });
  }
}
// 点击抽屉弹框
const visible = ref(false);
const drawStyle = ref( {})
const afterVisibleChange = bool => {
  console.log('visible', bool);
  if (!bool) {
    if(Array.isArray(formState.value.shipRoute)) {
      formState.value.shipRoute = formState.value.shipRoute.join(',')
    }
  }
};
const ganttInfo = ref({})
const formState = ref({
  id: '',
  createDate: '',
  createBy: '',
  orderNumber: null,
  ids: null,
  schemeId: '',
  schemeNumber: '',
  voyageNo: '',
  goodsNum: '',
  resourceContract: '',
  contractName: '',
  seller: '',
  tradeType:'',
  tradeBody: '',
  expectedLoadingDate: '',
  expectedLoadingCompletionWindow: '',
  expectedLoadingPort: '',
  shipName: '',
  imo: '',
  panamaCanalReservationDate: null,
  portChangeDateOne: null,
  portChangeDateTwo: null,
  shipChangeDateOne: null,
  shipChangeDateTwo: null,
  loadingCapacity: '',   // 总容量
  expectedUnloadingPort: '',
  expectedUnloadingWindow: '',
  indiaUnloadTime: '',
  europeUnloadTime: '',
  expectedFullLoadVoyageDays: '',
  expectedUnloadingCompletionWindow: '',
  expectedEmptyLoadVoyageDays: '',
  expectedEmptyReturnWindow: '',
  shipSpeed: '',
  quantityUnit: '',
  singleGoodsQuantity: '', //已装
  shipRoute: '',
  shipTradeBody: '',
  oilConsumption: '',
  shipContractName: '',
  shipContractId: '',
})
const ganttHistory = ref([])
const newHistory = ref({})
const showDrawer = (e) => {
  visible.value = true;
  ganttInfo.value = e.target.options
  formState.value = e.target.options
  if(Array.isArray(e.target.shipRoute)) {
    formState.value.shipRoute = e.target.shipRoute
  } else {
    formState.value.shipRoute = e.target.shipRoute? e.target.shipRoute.split(',') : ''
  }
  let obj = {
    schemeDetailId: e.target.dispatchSchemeDetailId.toString(),
    schemeId: e.target.schemeId.toString(),
    planId: e.target.planId.toString(),
    dataType: 2,
    createBy: localStorage.getItem('userName'),
  }
  proxy.$api.postGanttOneHistory(obj).then(res => {
    console.log('获取到历史记录没有', res)
    let newArr = res.resultObject
    newHistory.value = newArr[0]
    if (newArr.length > 1) {
      newArr.map((item, index) => {
        if (index > 0) {
          ganttHistory.value.push(item)
        }
      })
    }
  })
};
const childrenDrawer = ref(false);
const onClose = () => {
  childrenDrawer.value = false
};
const showChildrenDrawer = () => {
  childrenDrawer.value = true;
};
// 删除的逻辑
const labelCol = ref(
    {
      style: {
        width: '40px'
      },
    },
)
const wrapperCol = ref({
  span: 20
})

/**
 * 点击编辑保存
 * */
const onSubmitForm = () => {
  console.log('传的参数', formState.value)
  proxy.$api.getChartEdit(formState.value).then(res => {
    console.log('甘特图修改成功', res)
    ganttInfo.value = res.resultObject
    childrenDrawer.value = false
    emit('dropChangeVal', true)
  })
}
const caseForm = ref()
const deleteVisible = ref(false)
const showDeleteModal = () => {
  deleteVisible.value = true
  console.log('formAdd', caseForm.value)
};
const cacelDeleteModel = () =>{
  deleteVisible.value = false
  caseForm.value.resetFields()
}
const deleteFormState = ref({
  schemeDetailId: ganttInfo.value.id,
  reasonMsg: ''
})
const handleOk = () => {
  proxy.$api.deleteGanttOne(deleteFormState.value).then(res => {
    console.log('点击了删除', res)
    deleteVisible.value = false
    message.success('删除成功')
    emit('dropChangeVal', true)
  })
}
/**
 * 点击查看详情
 * */
const goHistoryInfo = (id) => {
  router.push({
    path: '/plan/schedulingHistory',
    query: {
      planId: id
    }
  })
}
onMounted(() => {
  try {
    setTimeout(() => {
      init()
      flagList()
    }, 500)
    setTimeout(() => {
      scaleUnit.value = sessionStorage.getItem('scaleUnitResArrge')
      toggleTimeDimension(scaleUnit.value)
    }, 1000)
  } catch (e) {
    console.log('错误', e)
  }

})
onBeforeUnmount(() => {
  if (gantt.value && ganttData.value.tableConfig.length > 0) {
    gantt.value.destroy()
  }
})
</script>

<style  lang="scss" scoped>
.hightChart-gantt {
  position: relative;
  #containerResArrge {
    //max-width: 12000px;
    width: 100%;
    height: 100%;
    margin: 0 auto;
  }
}
</style>
